'use client';

import { Button, Form, Input, Modal, Popconfirm, Space, InputNumber, Select, message } from 'antd';
import { useRef, useState, useEffect } from 'react';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { FriendlyLink } from '@/types/friendly-link';
import { getFriendlyLinkPage, createFriendlyLink, updateFriendlyLink, deleteFriendlyLink } from '@/apis/admin/friendly-link';

const FriendlyLinksPage = () => {
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>(null);
  const [isOpen, setIsOpen] = useState(false);
  const [editId, setEditId] = useState<string | null>(null);
  const [isClient, setIsClient] = useState(false);

  useEffect(() => setIsClient(true), []);

  const handleEdit = (record: FriendlyLink) => {
    setIsOpen(true);
    setEditId(record.id);
    form.setFieldsValue({ ...record });
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        name: values.name,
        url: values.url,
        order: Number(values.order) || 0,
        isActive: Number(values.isActive) || 1,
      };
      if (editId) {
        await updateFriendlyLink({ id: editId, ...payload });
        message.success('更新成功');
      } else {
        await createFriendlyLink(payload);
        message.success('创建成功');
      }
      setIsOpen(false);
      actionRef.current?.reload();
    } catch (error) {
      console.error(error);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteFriendlyLink(id);
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      console.error(error);
    }
  };

  const columns: ProColumns<FriendlyLink>[] = [
    { title: 'ID', dataIndex: 'id', search: false },
    { title: '名称', dataIndex: 'name' },
    { title: '链接', dataIndex: 'url', render: (_, record) => <a href={record.url} target="_blank" rel="noreferrer">{record.url}</a> },
    { title: '排序', dataIndex: 'order', search: false },
    { 
      title: '状态', 
      dataIndex: 'isActive', 
      valueEnum: { 1: { text: '启用' }, 0: { text: '禁用' } } 
    },
    { title: '创建时间', dataIndex: 'createdAt', valueType: 'dateTime', search: false },
    { title: '更新时间', dataIndex: 'updatedAt', valueType: 'dateTime', search: false },
    {
      title: '操作',
      key: 'action',
      search: false,
      render: (_: any, record: FriendlyLink) => (
        <Space size="middle">
          <a onClick={() => handleEdit(record)}>编辑</a>
          <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {isClient && (
        <>
          <ProTable<FriendlyLink>
            columns={columns}
            actionRef={actionRef}
            request={async (params) => {
              const page = params.current || 1;
              const pageSize = params.pageSize || 10;
              const name = params.name as string | undefined;
              const isActive = params.isActive as number | undefined;
              const { data, total } = await getFriendlyLinkPage({ page, pageSize, name, isActive });
              return { data, total };
            }}
            rowKey="id"
            search={{ labelWidth: 'auto' }}
            toolBarRender={() => [
              <Button
                key="add"
                type="primary"
                onClick={() => {
                  setIsOpen(true);
                  setEditId(null);
                  form.resetFields();
                }}
              >
                新增
              </Button>,
            ]}
          />
          <Modal title={editId ? '编辑友情链接' : '新增友情链接'} open={isOpen} onOk={handleOk} onCancel={() => setIsOpen(false)}>
            <Form form={form} layout="vertical">
              <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
                <Input />
              </Form.Item>
              <Form.Item label="链接" name="url" rules={[{ required: true, message: '请输入链接地址' }]}>
                <Input placeholder="https://example.com" />
              </Form.Item>
              <Form.Item label="排序" name="order" initialValue={0}>
                <InputNumber min={0} className="w-full" />
              </Form.Item>
              <Form.Item label="状态" name="isActive" initialValue={1}>
                <Select>
                  <Select.Option value={1}>启用</Select.Option>
                  <Select.Option value={0}>禁用</Select.Option>
                </Select>
              </Form.Item>
            </Form>
          </Modal>
        </>
      )}
    </div>
  );
};

export default FriendlyLinksPage;